package com.ning.common.web.interceptor;

import com.ning.common.util.JwtUtil;
import com.ning.common.web.exception.CustomerException;
import com.ning.common.web.response.ResultCode;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    /**
     * 如果未携带token或者token有误，则抛出异常
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");

        if (token==null||token.trim().equals("")) {
            throw new CustomerException(ResultCode.USER_NOT_LOGIN);
        }
        //查看是否过期、是否违法
        JwtUtil.checkSign(token);

        //取出token信息
        Map<String, Object> info = JwtUtil.getInfo(token);

        info.forEach((k,v)->{
            System.out.print("k = " + k+"\t");
            System.out.println("v = " + v);
        });

        return true;
    }
}
